package edu.uic.kott.activities;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
import java.util.List;

import edu.uic.keyoutcomestrackertool.R;
import edu.uic.kott.db.KottDataSource;
import edu.uic.kott.fragments.DatePickerFragment;
import edu.uic.kott.model.Compute;
import edu.uic.kott.model.Course;
import edu.uic.kott.model.Instructor;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddEditCourse extends FragmentActivity implements DatePickerFragment.DatePickerDialogListener{

	KottDataSource datasource;

	List<Instructor> instructorList;
	List<Instructor> taList;

	private static final int START_DATE_ID = 1;
	private static final int END_DATE_ID = 2;
	private static final String LOGTAG = "KOTT";

	private EditText classNameEditText;
	private EditText startDateEditText;	
	private EditText endDateEditText;
	private TextView daysTextView;
	private TextView timeTextView;
	private Button addDayTimeButton;
	private EditText targetedWssEditText;
	private EditText classLocationEditText;
	private Spinner instructorSpinner;
	private Button addInstructorTaButton;
	private Button helpButton;
	private Spinner taSpinner;

	private String id;
	private String className;
	private String startDate;
	private String endDate;
	private String days;
	private String startTime;
	private String endTime;
	private String tWSS;
	private String classLocation;
	private int instructorId;
	private int taId;
	private String option;				//to determine if the screen loaded to add new class or edit existing class 
	private boolean requiredFields;		//to make sure user has filled in all mandatory fields

	Bundle extras;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_edit_course);

		datasource = new KottDataSource(this);

		classNameEditText = (EditText) findViewById(R.id.courseNameEditText);
		startDateEditText = (EditText) findViewById(R.id.dateFirstClassEditText);
		daysTextView = (TextView) findViewById(R.id.classDayTimeTextView);
		timeTextView = (TextView) findViewById(R.id.timeTextView);
		addDayTimeButton = (Button) findViewById(R.id.addDayTimeButton);
		addDayTimeButton.setOnClickListener(selectDayTimeListener);
		endDateEditText = (EditText) findViewById(R.id.dateLastClassEditText);
		targetedWssEditText = (EditText) findViewById(R.id.weeklyStyduSessionsEditText);
		helpButton = (Button) findViewById(R.id.helpButton);
		classLocationEditText = (EditText) findViewById(R.id.classLocationEditText);

		instructorSpinner = (Spinner)findViewById(R.id.instructorSpinner);
		taSpinner = (Spinner)findViewById(R.id.taSpinner);

		//default values
		classLocation = "Not Available";
		instructorId = 0;
		taId = 0;

		option = "add";		//by default it is add new class

		extras = getIntent().getExtras();

		if (extras != null){
			Log.i(LOGTAG,"Inside AddEdit for updating course");

			option = extras.getString("option");

			Log.i(LOGTAG,"Option changed to " + option);			

			id = extras.getString("id");
			className = extras.getString("className");
			startDate = extras.getString("startDate");
			endDate = extras.getString("endDate");
			days = extras.getString("days");
			startTime = extras.getString("startTime");
			endTime = extras.getString("endTime");
			tWSS = extras.getString("tWSS");
			classLocation = extras.getString("classLocation");

			classNameEditText.setText(className);
			startDateEditText.setText(startDate);
			endDateEditText.setText(endDate);
			daysTextView.setText(days);
			timeTextView.setText(startTime + "  to  " + endTime);
			targetedWssEditText.setText(tWSS);

			if(!("Not Available".equalsIgnoreCase(classLocation)))
				classLocationEditText.setText(classLocation);
		}

		helpButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(AddEditCourse.this, Help.class));

			}
		});

		addInstructorTaButton = (Button) findViewById(R.id.addInstructorTaButton);
		addInstructorTaButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(AddEditCourse.this, AddEditInstructor.class);
				intent.putExtra("option", "back to AddEditCourse");
				startActivityForResult(intent, 104);				
			}
		});		

		datasource = new KottDataSource(this);

		refreshLists();
	}

	private void refreshLists(){
		instructorList = datasource.findAllByType("Instructor");
		ArrayAdapter<Instructor> instructorAdapter = new ArrayAdapter<Instructor>(this, android.R.layout.simple_spinner_item, instructorList);
		instructorSpinner.setAdapter(instructorAdapter);
		instructorSpinner.setOnItemSelectedListener(instructorListener);

		taList = datasource.findAllByType("Ta");				
		ArrayAdapter<Instructor> taAdapter = new ArrayAdapter<Instructor>(this, android.R.layout.simple_spinner_item, taList);
		taSpinner.setAdapter(taAdapter);
		taSpinner.setOnItemSelectedListener(taListener);
	}

	public void InputStartDate(View v) {
		DialogFragment newFragment = DatePickerFragment.newInstance(START_DATE_ID);
		newFragment.show(getFragmentManager(), "datePicker");
	}

	public void InputEndDate(View v) {
		DialogFragment newFragment = DatePickerFragment.newInstance(END_DATE_ID);
		newFragment.show(getFragmentManager(), "datePicker");
	}

	@Override
	public void onDateSet(int id, DatePicker view, int year, int month, int day) {
		Log.i("DatePicker", "Date picker set from id " + id + "!");

		switch (id) {
		case 1:
			startDateEditText.setText(String.valueOf(month+1)+"/"+String.valueOf(day)+"/"+String.valueOf(year));
			break;

		case 2:
			endDateEditText.setText(String.valueOf(month+1)+"/"+String.valueOf(day)+"/"+String.valueOf(year));
			break;
		}		
		try {
			compareDate();
		} catch (ParseException e) {
			e.printStackTrace();
		}		 
	}

	@SuppressLint("SimpleDateFormat")
	public void compareDate() throws ParseException{

		if((startDateEditText.length() >0) && (endDateEditText.length() >0) ){

			Toast msg;
			String sDate = startDateEditText.getText().toString();
			String eDate = endDateEditText.getText().toString();		

			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

			Date startDate = sdf.parse(sDate);
			Date endDate =  sdf.parse(eDate);

			if(startDate.compareTo(endDate)>=0)
				msg = Toast.makeText(this, "INCORRECT", Toast.LENGTH_SHORT);
			else
				msg = Toast.makeText(this, "CORRECT", Toast.LENGTH_SHORT);

			msg.show();
		}
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_save, menu);		
		return true;
	}

	AdapterView.OnItemSelectedListener instructorListener = new AdapterView.OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			Instructor instructor = (Instructor) parent.getItemAtPosition(position);
			instructorId = (int) instructor.getInstructorId();
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			instructorId = 0;				
		}			
	};

	AdapterView.OnItemSelectedListener taListener = new AdapterView.OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			Instructor instructor = (Instructor) parent.getItemAtPosition(position);
			taId = (int) instructor.getInstructorId();
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			taId = 0;				
		}			
	};


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		requiredFields = true;

		if(classNameEditText.getText().toString().length() > 0)
			className = classNameEditText.getText().toString();
		else requiredFields = false;

		if(startDateEditText.getText().toString().length() > 0)
			startDate = startDateEditText.getText().toString();
		else requiredFields = false;

		if(endDateEditText.getText().toString().length() > 0)
			endDate = endDateEditText.getText().toString();
		else requiredFields = false;

		if(daysTextView.getText().toString().length() > 0)
			days = daysTextView.getText().toString();
		else requiredFields = false;

		if(targetedWssEditText.getText().toString().length() > 0)
			tWSS = targetedWssEditText.getText().toString();
		else requiredFields = false;

		if(classLocationEditText.getText().toString().length() > 0)
			classLocation = classLocationEditText.getText().toString();
		else classLocation = "Not Available";

		Log.i(LOGTAG, "classLocation is: " + classLocation);

		if(requiredFields == true){
			//Intent intent = new Intent(this, Courses.class);
			Course course = new Course();
			course.setCourseName(className);
			course.setStartDate(startDate);
			course.setEndDate(endDate);
			course.setClassDays(days);
			course.setStartTime(startTime);
			course.setEndTime(endTime);
			course.setTargetedWSS(tWSS);
			course.setClassLocation(classLocation);
			course.setInstructor(String.valueOf(instructorId));
			course.setTa(String.valueOf(taId));

			Compute c = new Compute();
			//returns list of dates on which class will be scheduled between start and end dates
			List<String> classDates = c.getDateList(startDate, endDate, days);
			
			for(int i=0; i<classDates.size();i++)
				Log.i(LOGTAG, "class date added :" + classDates.get(i));

			if("update".equalsIgnoreCase(option)){
				Log.i(LOGTAG,"Call courseUpdate()");
				Log.i(LOGTAG,"Course to be updated is " + String.valueOf(id));

				course.setCourseId(Long.parseLong(id));
				datasource.updateCourse(course);
				datasource.updateDates(id, classDates);				
			}

			if("add".equalsIgnoreCase(option)){
				long courseId = datasource.createCourse(course);
				Log.i(LOGTAG,"Course " + course.getCourseName() + " created with id " + courseId);
				datasource.addDates(String.valueOf(courseId), classDates);
			}			

			//startActivity(intent);
			finish();			
		}
		else{

			AlertDialog.Builder builder = new AlertDialog.Builder(AddEditCourse.this);
			builder.setTitle(R.string.dialogTitle_requiredFields);	//set message title from string resource
			builder.setMessage(R.string.dialogMsg_requiredFields);//set message content
			builder.setPositiveButton("OK", null);		//ok button to dismiss the dialog box

			AlertDialog errorDialog = builder.create();
			errorDialog.show();
		}
		return super.onOptionsItemSelected(item);
	}

	private OnClickListener selectDayTimeListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(AddEditCourse.this, DayTime.class);
			startActivityForResult(intent, 103);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {		
		super.onActivityResult(requestCode, resultCode, intent);

		if(requestCode == 103 && resultCode == RESULT_OK){
			days = intent.getStringExtra("days");
			startTime = intent.getStringExtra("startTime");
			endTime = intent.getStringExtra("endTime");

			Log.i(LOGTAG, days +" \n " + startTime + " " + endTime);

			daysTextView.setText(days);
			timeTextView.setText(startTime + "  to  " + endTime);
		}

		if(requestCode == 104 && resultCode == RESULT_OK){
			refreshLists();
		}

	}
}